#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Project: devops
#  Author: an00
#  Create: 2018/8/4 20:49


import django_filters
from django.db.models import Q
from servers.models import Server


class ServerFilter(django_filters.rest_framework.FilterSet):
    """
    服务器过滤类
    """

    hostname = django_filters.CharFilter(method='search_server')
    idc = django_filters.NumberFilter(method="search_idc")
    cabinet = django_filters.NumberFilter(method="search_cabinet")
    business_parent = django_filters.NumberFilter(method="search_first_business")
    business_line = django_filters.NumberFilter(method="search_second_business")
    # server_type = django_filters.ChoiceFilter(name="server_type", choices=((0,"vm"), (1, "物理机"),(2, "宿主机")),
    #                                           lookup_expr="exact")

    # def search_server_type(self,queryset, name, value):
    #     if value == 0:
    #         return queryset.filter(server_type__in=[0,1])
    #     else:
    #         return queryset.filter(server_type=value)

    def search_second_business(self, queryset, name, value):
        if value > 0:
            return queryset.filter(business_line_id__exact=value)
        elif value == -1:
            return queryset.filter(business_line_id__isnull=True)
        else:
            return queryset

    def search_first_business(self, queryset, name, value):
        if value > 0:
            return queryset.filter(business_parent_id__exact=value)
        elif value == -1:
            return queryset.filter(business_parent_id__isnull=True)
        else:
            return queryset

    def search_server(self, queryset, name, value):
        return queryset.filter(Q(hostname__icontains=value) | Q(ip__icontains=value))

    def search_idc(self, queryset, name, value):
        if value > 0:
            return queryset.filter(idc_id__exact=value)
        elif value == -1:
            return queryset.filter(idc_id__isnull=True)
        else:
            return queryset

    def search_cabinet(self, queryset, name, value):
        if value > 0:
            return queryset.filter(cabinet_id__exact=value)
        elif value == -1:
            return queryset.filter(cabinet_id__isnull=True)
        else:
            return queryset

    class Meta:
        model = Server
        # fields = ['hostname', 'idc', 'cabinet', "business_parent_id", "business_line", "server_type"]
        fields = ['hostname', 'idc', 'cabinet', "business_parent_id", "business_line"]
